//
//  SettingPanelBuilder.m
//  Rongcloud
//
//  Created by LiuLinhong on 2017/09/12.
//  Copyright © 2017年 Beijing Rongcloud Network Technology Co. , Ltd. All rights reserved.
//

#import "SettingPanelBuilder.h"
#import "LogonViewController.h"
#import "CommonUtility.h"

@interface SettingPanelBuilder () <NSComboBoxDelegate>
{
    NSUserDefaults *settingUserDefaults;
    NSInteger originalResolutionIndex;
}

@property (nonatomic, strong) LogonViewController *logonViewController;
@property (nonatomic, strong) NSPanel *settingContentPanel;
@property (nonatomic, assign) BOOL isOpenSettingPanel;
@property (nonatomic, strong) NSComboBox *frameRateCombobox, *sessionTypeCombobox, *codeTypeCombobox, *srtpCombobox, *codeRateMaxCombobox, *codeRateMinCombobox;
@property (nonatomic, strong) NSSlider *codeRateMaxSlider, *codeRateMinSlider;
@property (nonatomic, strong) NSTextField *codeRateMaxTextField, *codeRateMinTextField;
@property (nonatomic, strong) NSTextField *appkenTextField, *tokenURLTextField, *cmpURLTextField;
@property (nonatomic, strong) NSArray *codeRateArray;
@property (nonatomic, assign) NSInteger maxValue, minValue, defaultValue, stepValue;
@property (nonatomic, strong) NSTextField *tipMessageTextField;

@end

@implementation SettingPanelBuilder

- (instancetype)initWithViewController:(NSViewController *)vc
{
    self = [super init];
    if (self)
    {
        self.logonViewController = (LogonViewController *) vc;
        self.isOpenSettingPanel = NO;
        self.codeRateArray = [CommonUtility getPlistArrayByplistName:Key_CodeRate];
        settingUserDefaults = [LogonViewController shareSettingUserDefaults];
        originalResolutionIndex = self.logonViewController.resolutionRatioIndex;
        
        [self initSettingPanel];
        
        [self initReleaseSettingView];
    }
    return self;
}

- (void)initSettingPanel
{
    self.settingContentPanel = [[NSPanel alloc] initWithContentRect:CGRectMake(0, 0, 400, 190) styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreNonretained defer:YES];
    self.settingContentPanel.title = @"参数设置";
    self.settingContentPanel.floatingPanel = YES;
    [self.settingContentPanel center];
    
    //左下角 Debug:参数设置按钮  Release:自定义CMP/Token/AppKey
    NSButton *openSettingButton = [[NSButton alloc] initWithFrame:CGRectMake(0, 0, 18, 18)];
    openSettingButton.title = @"";
    openSettingButton.font = [NSFont systemFontOfSize:14.0];
    openSettingButton.bezelStyle = NSBezelStyleTexturedRounded;
    openSettingButton.bordered = NO;
    [(NSButtonCell *)openSettingButton.cell setHighlightsBy:NSNoCellMask];
    [openSettingButton setTarget:self];
    [openSettingButton setAction:@selector(showSettingPanel)];
    [self.logonViewController.logonViewBuilder.backgroundImageView addSubview:openSettingButton];
}

- (void)initLabel:(CGRect)frame withTitle:(NSString *)title
{
    NSTextField *frameRateTextField = [[NSTextField alloc] initWithFrame:frame];
    frameRateTextField.stringValue = title;
    frameRateTextField.bordered = NO;
    frameRateTextField.editable = NO;
    frameRateTextField.alignment = NSTextAlignmentRight;
    frameRateTextField.font = [NSFont systemFontOfSize:14.0];
    frameRateTextField.backgroundColor = [NSColor clearColor];
    [self.settingContentPanel.contentView addSubview:frameRateTextField];
}

#pragma mark - release模式页面
- (void)initReleaseSettingView
{
    [self initLabel:CGRectMake(10, self.settingContentPanel.frame.size.height - 65, 80, 20) withTitle:@"APP Key"];
    [self initLabel:CGRectMake(10, self.settingContentPanel.frame.size.height - 105, 80, 20) withTitle:@"Token URL"];
    [self initLabel:CGRectMake(10, self.settingContentPanel.frame.size.height - 145, 80, 20) withTitle:@"CMP URL"];
    
    self.tipMessageTextField = [[NSTextField alloc] initWithFrame:CGRectMake(0, self.settingContentPanel.frame.size.height - 173, self.settingContentPanel.frame.size.width, 20)];
    self.tipMessageTextField.bordered = NO;
    self.tipMessageTextField.editable = NO;
    self.tipMessageTextField.alignment = NSTextAlignmentCenter;
    self.tipMessageTextField.font = [NSFont systemFontOfSize:14.0];
    self.tipMessageTextField.backgroundColor = [NSColor clearColor];
    self.tipMessageTextField.textColor = [NSColor redColor];
    [self.settingContentPanel.contentView addSubview:self.tipMessageTextField];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *customAppKey = [userDefaults valueForKey:kCustomAPPKey];
    NSString *customTokenURL = [userDefaults valueForKey:kCustomTokenURL];
    NSString *customCmpURL = [userDefaults valueForKey:kCustomCMPURL];
    
    self.appkenTextField = [[NSTextField alloc] initWithFrame:CGRectMake(100, self.settingContentPanel.frame.size.height - 70, 260, 30)];
    self.appkenTextField.bezelStyle = NSTextFieldRoundedBezel;
    self.appkenTextField.alignment = NSTextAlignmentLeft;
    self.appkenTextField.font = [NSFont systemFontOfSize:14.0];
    if (customAppKey)
        self.appkenTextField.stringValue = customAppKey;
    //    self.appkenTextField.target = self.logonContentView;
    //    self.appkenTextField.action = @selector(roomNumberTextFieldDidChange:);
    //    self.appkenTextField.delegate = self.logonViewController;
    [self.settingContentPanel.contentView addSubview:self.appkenTextField];
    
    self.tokenURLTextField = [[NSTextField alloc] initWithFrame:CGRectMake(100, self.settingContentPanel.frame.size.height - 110, 260, 30)];
    self.tokenURLTextField.bezelStyle = NSTextFieldRoundedBezel;
    self.tokenURLTextField.alignment = NSTextAlignmentLeft;
    self.tokenURLTextField.font = [NSFont systemFontOfSize:14.0];
    if (customTokenURL)
        self.tokenURLTextField.stringValue = customTokenURL;
    //    self.tokenURLTextField.target = self.logonContentView;
    //    self.tokenURLTextField.action = @selector(roomNumberTextFieldDidChange:);
    //    self.tokenURLTextField.delegate = self.logonViewController;
    [self.settingContentPanel.contentView addSubview:self.tokenURLTextField];
    
    self.cmpURLTextField = [[NSTextField alloc] initWithFrame:CGRectMake(100, self.settingContentPanel.frame.size.height - 150, 260, 30)];
    self.cmpURLTextField.bezelStyle = NSTextFieldRoundedBezel;
    self.cmpURLTextField.alignment = NSTextAlignmentLeft;
    self.cmpURLTextField.font = [NSFont systemFontOfSize:14.0];
    if (customCmpURL)
        self.cmpURLTextField.stringValue = customCmpURL;
    //    self.cmpURLTextField.target = self.logonContentView;
    //    self.cmpURLTextField.action = @selector(roomNumberTextFieldDidChange:);
    //    self.cmpURLTextField.delegate = self.logonViewController;
    [self.settingContentPanel.contentView addSubview:self.cmpURLTextField];
    
    NSButton *saveSettingButton = [[NSButton alloc] initWithFrame:CGRectMake((self.settingContentPanel.frame.size.width/2-100)/2, 10, 100, 24)];
    saveSettingButton.title = @"保存";
    saveSettingButton.font = [NSFont systemFontOfSize:14.0];
    saveSettingButton.bezelStyle = NSBezelStyleRounded;
    [(NSButtonCell *)saveSettingButton.cell setHighlightsBy:NSPushInCellMask];
    [saveSettingButton setTarget:self];
    [saveSettingButton setAction:@selector(saveSettingButtonPressed)];
    [self.settingContentPanel.contentView addSubview:saveSettingButton];
    
    
    NSButton *clearSettingButton = [[NSButton alloc] initWithFrame:CGRectMake(self.settingContentPanel.frame.size.width/2 + (self.settingContentPanel.frame.size.width/2-100)/2, 10, 100, 24)];
    clearSettingButton.title = @"清空";
    clearSettingButton.font = [NSFont systemFontOfSize:14.0];
    clearSettingButton.bezelStyle = NSBezelStyleRounded;
    [(NSButtonCell *)clearSettingButton.cell setHighlightsBy:NSPushInCellMask];
    [clearSettingButton setTarget:self];
    [clearSettingButton setAction:@selector(clearSettingButtonPressed)];
    [self.settingContentPanel.contentView addSubview:clearSettingButton];
}

- (void)reloadChoiceData:(NSInteger)resolutionRatioIndex
{
    NSDictionary *codeRateDictionary = self.codeRateArray[resolutionRatioIndex];
    self.maxValue = [codeRateDictionary[Key_Max] integerValue];
    self.minValue = [codeRateDictionary[Key_Min] integerValue];
    self.defaultValue = [codeRateDictionary[Key_Default] integerValue];
    self.stepValue = [codeRateDictionary[Key_Step] integerValue];
    
    if (originalResolutionIndex != resolutionRatioIndex)
    {
        originalResolutionIndex = resolutionRatioIndex;
        self.logonViewController.codeRateMaxIndex = self.defaultValue/10;
        
        switch (self.logonViewController.resolutionRatioIndex)
        {
            case 0:
                self.logonViewController.codeRateMinIndex = 5;
                break;
            case 1:
                self.logonViewController.codeRateMinIndex = 5;
                break;
            case 2:
                self.logonViewController.codeRateMinIndex = 5;
                break;
            default:
                self.logonViewController.codeRateMinIndex = 5;
                break;
        }
        [settingUserDefaults setObject:@(self.logonViewController.codeRateMaxIndex) forKey:Key_CodeRate];
        [settingUserDefaults setObject:@(self.logonViewController.codeRateMinIndex) forKey:Key_CodeRateMin];
        [settingUserDefaults synchronize];
    }
    
    //最大码率
    [self.codeRateMaxCombobox removeAllItems];
    NSMutableArray *muArray = [NSMutableArray array];
    for (NSInteger temp = 0; temp <= self.maxValue; temp += self.stepValue)
    {
        [self.codeRateMaxCombobox addItemWithObjectValue:[NSString stringWithFormat:@"%zd", temp]];
        [muArray addObject:[NSString stringWithFormat:@"%zd", temp]];
    }
    [self.codeRateMaxCombobox selectItemAtIndex:self.logonViewController.codeRateMaxIndex];
    
    //最小码率
    [self.codeRateMinCombobox removeAllItems];
    for (NSInteger temp = 0; temp <= self.maxValue; temp += self.stepValue)
        [self.codeRateMinCombobox addItemWithObjectValue:[NSString stringWithFormat:@"%zd", temp]];
    [self.codeRateMinCombobox selectItemAtIndex:self.logonViewController.codeRateMinIndex];
}

#pragma mark - 打开参数设置Panel
- (void)showSettingPanel
{
    if (self.isOpenSettingPanel)
        [self closeSettingPanel];
    else
        [self.settingContentPanel makeKeyAndOrderFront:nil];
    
    self.isOpenSettingPanel = !self.isOpenSettingPanel;
}

#pragma mark - 关闭参数设置Panel
- (void)closeSettingPanel
{
    [self.settingContentPanel orderOut:nil];
    [self.logonViewController.view.window orderFront:nil];
}

- (void)saveSettingButtonPressed
{
    NSString *appKey = self.appkenTextField.stringValue;
    NSString *cmpURL = self.cmpURLTextField.stringValue;
    NSString *tokenURL = self.tokenURLTextField.stringValue;
    
    if ([[appKey stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""] || [[cmpURL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""] || [[cmpURL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:@""])
    {
        self.tipMessageTextField.stringValue = @"APP Key, Token URL, CMP URL均不能为空";
        return;
    }
    if (![tokenURL containsString:@"."] || ![tokenURL containsString:@":"])
    {
        self.tipMessageTextField.stringValue = @"token格式错误";
        return;
    }
    if (![cmpURL containsString:@"."] || ![cmpURL containsString:@":"])
    {
        self.tipMessageTextField.stringValue = @"cmp格式错误";
        return;
    }
    
    [self closeSettingPanel];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:appKey forKey:kCustomAPPKey];
    [userDefaults setObject:tokenURL forKey:kCustomTokenURL];
    [userDefaults setObject:cmpURL forKey:kCustomCMPURL];
    [userDefaults synchronize];
    
    [self.logonViewController queryKeyTokenInRelease];
}

- (void)clearSettingButtonPressed
{
    [self closeSettingPanel];
    
    self.appkenTextField.stringValue = @"";
    self.tokenURLTextField.stringValue = @"";
    self.cmpURLTextField.stringValue = @"";
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:@"" forKey:kCustomAPPKey];
    [userDefaults setObject:@"" forKey:kCustomTokenURL];
    [userDefaults setObject:@"" forKey:kCustomCMPURL];
    [userDefaults synchronize];
    
    [self.logonViewController queryKeyTokenInRelease];
}

@end
